package cn.wk.libs4a.view.adview;

import java.util.ArrayList;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.TextView;
import cn.wk.libs4a.R;

/**
 * 滑动广告方法
 * 
 * xml中： <include android:id="@+id/ad_view" layout="@layout/wk_view_adview" />
 * 
 * 代码中： adView = new ADViewUtils(this, view);
 * 
 * 设置数据：setData(ArrayList<ADViewBean> list)
 * 
 * @date 2015-3-4 上午10:37:06
 */
public class ADViewUtils {

	private View v;
	private Context ctx;

	// 顶部的ViewPager
	private ViewPager viewpager;
	private CircleFlowIndicator flowIndicator;
	private ADPaperAdapter mHomeGalleryAdapter;
	private long time = 3 * 1000;
	// 自动滚动
	private Handler mPagerHandler;
	private Runnable mAutoPlayTask = new Runnable() {
		@Override
		public void run() {
			if (viewpager.getCurrentItem() < mHomeGalleryAdapter.getCount() - 1) {
				viewpager.setCurrentItem(viewpager.getCurrentItem() + 1);
			} else {
				viewpager.setCurrentItem(0);
			}
			mPagerHandler.postDelayed(mAutoPlayTask, time);
		}
	};

	/**
	 * 初始化ADView
	 * 
	 * @param ctx
	 * @param v
	 *            父view
	 */
	public ADViewUtils(Context ctx, View v) {
		this.ctx = ctx;
		this.v = v;

		viewpager = (ViewPager) v.findViewById(R.id.gallery);
		flowIndicator = (CircleFlowIndicator) v
				.findViewById(R.id.circleFlowIndicator);
		mHomeGalleryAdapter = new ADPaperAdapter(ctx);
		viewpager.setAdapter(mHomeGalleryAdapter);
		
	}

	public ADViewUtils(Context ctx, View v, boolean clickable) {
		this.ctx = ctx;
		this.v = v;

		viewpager = (ViewPager) v.findViewById(R.id.gallery);
		flowIndicator = (CircleFlowIndicator) v
				.findViewById(R.id.circleFlowIndicator);
		mHomeGalleryAdapter = new ADPaperAdapter(ctx, false);
		viewpager.setAdapter(mHomeGalleryAdapter);
	}

	/**
	 * 设置自动滚动
	 */
	public void setAutoScroll() {
		mPagerHandler = new Handler();
		mPagerHandler.postDelayed(mAutoPlayTask, time);
	}

	/**
	 * 设置数据
	 */
	public void setData(ArrayList<ADViewBean> list) {
		mHomeGalleryAdapter.setData(list);
		flowIndicator.setGallery(mHomeGalleryAdapter.getCount());
		viewpager.setCurrentItem(0);
		viewpager.setOnPageChangeListener(new CommentPageChangeListener());
	}

	class CommentPageChangeListener implements OnPageChangeListener {
		public void onPageScrollStateChanged(int arg0) {
		}
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}
		public void onPageSelected(int position) {
			flowIndicator.setPosition(position);
		}
	}

}
